package pri.damai.xiaowu.goods.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pri.damai.xiaowu.common.core.util.ExceptionUtil;
import pri.damai.xiaowu.goods.common.command.StockReduceCmd;
import pri.damai.xiaowu.goods.server.dao.ProductSkuDao;
import pri.damai.xiaowu.goods.server.entity.ProductSku;
import pri.damai.xiaowu.goods.server.service.ProductSkuService;

import javax.annotation.Resource;
import java.util.List;

/**
 * sku表(ProductSku)表服务实现类
 * @Desc
 * @Author DaMai
 * @Date 2022-03-22 15:22:18
 */
@Service("productSkuService")
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuDao, ProductSku> implements ProductSkuService {

    @Resource
    ProductSkuDao productSkuDao;

    public LambdaQueryWrapper<ProductSku> getLambda() {
        return new LambdaQueryWrapper<>();
    }

    @Transactional(rollbackFor = Exception.class)
    public void reduceSkuStock(List<StockReduceCmd> stockReduceCmds) {
        stockReduceCmds.forEach(this::reduceSkuStock);
    }

    public void reduceSkuStock(StockReduceCmd stockReduceCmd) {

        ProductSku productSku = this.getById(stockReduceCmd.getSkuId());

        ExceptionUtil.ifTureThrow(
                productSku.getStockNum() <= 0 || productSku.getStockNum() - stockReduceCmd.getReduceNum() < 0
                , "库存余额不足。"
        );

        Integer updateResult = productSkuDao.reduceStock(stockReduceCmd.getSkuId(), stockReduceCmd.getReduceNum());

        ExceptionUtil.ifTureThrow(updateResult <= 0, "库存余额不足。");
    }
}
